package com.heba.greenmulu;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.heba.ATApp;
import com.heba.AppManager;
import com.heba.dialog.MyProgressDialog;
import com.heba.utils.DensityUtils;
import com.heba.utils.StatusBarUtils;
import com.heba.view.Loading;
import com.leaf.library.StatusBarUtil;
import com.scwang.smartrefresh.layout.api.RefreshLayout;


/**
 * 基类
 * <p>
 * Created by shenghao on 2015/5/18.
 */
public abstract class BaseActivity extends AppCompatActivity {

    /**
     * tag
     */
    protected final String TAG = this.getClass().getSimpleName();

    protected Context mContext;

    /**
     * 屏幕宽高
     */
    protected int ScreenWidth = 0;   //屏幕宽度
    protected int ScreenHeight = 0;  //屏幕高度

    /**
     * 刷新框架分页显示
     */
    protected int PerPage = 20;   //每页加载的数据
    protected int Page = 1;   //加载页

    /**
     * PullToRefreshListView加载
     */
    protected boolean firstRefresh = true;   //判断是否第一次刷新
    protected boolean isRefreshFromTop = false;  //判断是否下拉刷新
    protected boolean isLoadMore = true;     //加载更多

    /**
     * title bar
     */
    protected TextView txt_title;
    protected ImageView img_back;
    protected TextView txt_right;
    protected ImageView img_right;
    protected ConstraintLayout titleBar;

    /**
     * //加载框
     */
    protected MyProgressDialog progressDialog;
    protected Loading loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        super.onCreate(savedInstanceState);
        mContext = this;
        ATApp.setAppLanguage();
        //android O fix bug orientation
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        //activity被回收
        if (null != savedInstanceState) {
        }

        AppManager.getAppManager().addActivity(this);
        init();

    }

    @SuppressLint("ResourceAsColor")
    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {



        /**
         * 实现APP黑白化效果
         */
//        if ("FrameLayout".equals(name)) {
//            int count = attrs.getAttributeCount();
//            for (int i = 0; i < count; i++) {
//                String attributeName = attrs.getAttributeName(i);
//                String attributeValue = attrs.getAttributeValue(i);
//                if (attributeName.equals("id")) {
//                    int id = Integer.parseInt(attributeValue.substring(1));
//                    String idVal = getResources().getResourceName(id);
//                    if ("android:id/content".equals(idVal)) {
//                        GrayFrameLayout grayFrameLayout = new GrayFrameLayout(context, attrs);
//                        return grayFrameLayout;
//                    }
//                }
//            }
//        }
        return super.onCreateView(name, context, attrs);
    }

    /**
     * onStop之前调用，用于保存信息
     *
     * @param outState
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //注释掉，让其不再保存Fragment的状态，达到其随着Activity一起被回收的效果！
        super.onSaveInstanceState(outState);
    }

    /**
     * init
     */
    private void init() {
        ScreenWidth = DensityUtils.getWidth(this);
        ScreenHeight = DensityUtils.getHeight(this);
        loading = new Loading(this);
        progressDialog = new MyProgressDialog(this, getResources().getString(R.string.loading));
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        /**
         * 移除堆栈(Stack)中的activity
         */
        AppManager.getAppManager().removeActivityFromStack(this);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        StatusBarUtils.setStatusLightMode(this);
    }

    /**
     * 绑定控件id
     */
    protected abstract void findViewById();

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 初始化topbar
     */
    protected void initTopbar() {
        txt_title = findViewById(R.id.txt_title);
        img_back = findViewById(R.id.img_back);
        txt_right = findViewById(R.id.txt_right);
        img_right = findViewById(R.id.img_right);
        titleBar = findViewById(R.id.title_bar);
        if (titleBar!=null){
            titleBar.setForceDarkAllowed(false);
        }
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });
    }

    /**
     * 通过类名启动Activity
     *
     * @param pClass
     */
    protected void openActivity(Class<?> pClass) {
        openActivity(pClass, null);
    }

    /**
     * 通过类名启动Activity，并且含有Bundle数据
     *
     * @param pClass
     * @param pBundle
     */
    protected void openActivity(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(this, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        startActivity(intent);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    /**
     * 进入activity添加fade in动画
     *
     * @param pClass
     * @param pBundle
     */
    protected void openActivityWithFadeInAnimation(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(this, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        startActivity(intent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    /**
     * 动画退出activity
     */
    protected void finishActivityWithFadeInAnimation() {
        finish();
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }


    /**
     * 通过Action启动Activity
     *
     * @param pAction
     */
    protected void openActivity(String pAction) {
        openActivity(pAction, null);
    }

    /**
     * 通过Action启动Activity
     *
     * @param pAction
     * @param url
     */
    protected void openActivityFromUri(String pAction, String url) {
        Intent intent = new Intent(pAction, Uri.parse(url));
        startActivity(intent);
    }

    /**
     * 通过Action启动Activity，并且含有Bundle数据
     *
     * @param pAction
     * @param pBundle
     */
    protected void openActivity(String pAction, Bundle pBundle) {
        Intent intent = new Intent(pAction);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        startActivity(intent);
    }

    /**
     * 具有动画效果
     * <p>
     * 结束Activity
     */
    protected void finishActivity() {
        finish();
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }

    @Override
    public Resources getResources() {
        /**
         * 设置字体大小不随系统设置而改变
         */
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    /**
     * 关闭刷新加载
     *
     * @param refreshLayout
     */
    protected void closeRefreshView(RefreshLayout refreshLayout) {
        if (refreshLayout.getState().isOpening) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
    }

    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent me) {
        if (me.getAction() == MotionEvent.ACTION_DOWN) {  //把操作放在用户点击的时候
            View v = getCurrentFocus();      //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
            if (isShouldHideKeyboard(v, me)) { //判断用户点击的是否是输入框以外的区域
                hideKeyboard(v.getWindowToken());   //收起键盘
            }
        }
        return super.dispatchTouchEvent(me);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {  //判断得到的焦点控件是否包含EditText
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],    //得到输入框在屏幕中上下左右的位置
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击位置如果是EditText的区域，忽略它，不收起键盘。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

}
